import React from 'react';
import { Box, Grid, Typography, Button } from '@mui/material';
import { useQuery } from 'react-query';
import { Plans } from 'api/queries';
import { useDarkMode } from 'contexts/DarkMode';
import { useTranslation } from 'react-i18next';
import AdaptiveLayout from 'components/elements/AdaptiveLayout';
import ReferralActionButtons from 'components/ecosystems/ReferralActionButtons';
import SliderInfo from 'components/electrons/SliderInfo';
import IOSAppStoreCard from 'components/ui/IOSAppStoreCard';
import Loader from 'components/atoms/Loader';
import { styled } from '@mui/material/styles';

// Styled components for the plan cards
const PlanTitle = styled(Typography)(({ theme, expanded }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: expanded ? '4.5rem' : '2rem', // Much larger when expanded
  fontWeight: expanded ? '800' : '700',
  color: '#ffffff',
  textAlign: 'center',
  width: '100%',
  letterSpacing: expanded ? '1px' : '0.5px',
  textShadow: '0 0 10px rgba(255, 255, 255, 0.3)', // Subtle white shadow
  transition: 'all 0.3s ease',
  lineHeight: expanded ? '1.1' : '1.3',
  marginBottom: expanded ? '16px' : '0',
  [theme.breakpoints.down('md')]: {
    fontSize: expanded ? '3.75rem' : '1.75rem',
  },
  [theme.breakpoints.down('sm')]: {
    fontSize: expanded ? '3rem' : '1.75rem',
  }
}));

const PlanSubtitle = styled(Typography)(({ theme, expanded }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: expanded ? '2.5rem' : '1.1rem', // Much larger when expanded
  fontWeight: expanded ? '600' : '500',
  color: '#ffffff',
  textAlign: 'center',
  width: '100%',
  textShadow: '0 0 8px rgba(255, 255, 255, 0.3)', // Subtle white shadow
  transition: 'all 0.3s ease',
  lineHeight: expanded ? '1.2' : '1.4',
  [theme.breakpoints.down('md')]: {
    fontSize: expanded ? '2rem' : '1.1rem',
  },
  [theme.breakpoints.down('sm')]: {
    fontSize: expanded ? '1.75rem' : '0.95rem',
  }
}));

// Business-themed CTA section styling
const CtaContainer = styled(Box)(({ theme }) => ({
  padding: theme.spacing(4, 2),
  textAlign: 'center',
  backgroundColor: '#f8fafc',
  borderRadius: '8px',
  margin: '16px auto 24px',
  maxWidth: '600px',
}));

const CtaTitle = styled(Typography)(({ theme }) => ({
  fontFamily: '"Poppins", "Roboto", sans-serif',
  fontSize: '1.5rem',
  fontWeight: '600',
  color: '#2d3748',
  marginBottom: theme.spacing(2),
}));

const CtaDescription = styled(Typography)(({ theme }) => ({
  fontSize: '1rem',
  color: '#718096',
  marginBottom: theme.spacing(3),
}));

const CtaButton = styled(Button)(({ theme }) => ({
  backgroundColor: '#0fa0af',
  color: 'white',
  textTransform: 'none',
  padding: '10px 24px',
  fontSize: '0.95rem',
  fontWeight: 500,
  borderRadius: '8px',
  boxShadow: 'none',
  '&:hover': {
    backgroundColor: '#0d8e9c',
    boxShadow: 'none',
  }
}));

const HomePage = () => {
  const { darkMode } = useDarkMode();
  const { t } = useTranslation();
  
  // Plans query to get the plan data
  const plansQuery = useQuery(
    "Plans",
    Plans,
    { retry: false }
  );
  
  // Function to create component props for plan cards
  const createPlanTitleComponent = (plan) => (
    <PlanTitle>
      {plan.title.toUpperCase()}
    </PlanTitle>
  );
  
  const createExpandedPlanTitleComponent = (plan) => (
    <PlanTitle expanded>
      {plan.title.toUpperCase()}
    </PlanTitle>
  );
  
  const createPlanSubtitleComponent = (plan) => {
    // Format price for display
    const currency = plan.currency === 'usd' ? '$' : plan.currency === 'eur' ? '€' : '£';
    const formattedPrice = `${currency}${plan.price}${plan.monthly ? '/month' : '/year'}`;
    
    // Get the first feature as the main benefit
    const mainFeature = plan.features && plan.features.length > 0 
      ? t(plan.features[0])
      : 'Premium Features';
      
    return (
      <PlanSubtitle>
        {`${mainFeature} • ${formattedPrice}`}
      </PlanSubtitle>
    );
  };
  
  const createExpandedPlanSubtitleComponent = (plan) => {
    // Format price for display
    const currency = plan.currency === 'usd' ? '$' : plan.currency === 'eur' ? '€' : '£';
    const formattedPrice = `${currency}${plan.price}${plan.monthly ? '/month' : '/year'}`;
    
    // Get the first feature as the main benefit
    const mainFeature = plan.features && plan.features.length > 0 
      ? t(plan.features[0])
      : 'Premium Features';
      
    return (
      <PlanSubtitle expanded>
        {`${mainFeature} • ${formattedPrice}`}
      </PlanSubtitle>
    );
  };
  
  // Prepare plan cards based on query data
  let monthlyPlans = [];
  
  if (plansQuery.data?.data?.plans) {
    monthlyPlans = plansQuery.data.data.plans.filter(p => p.monthly);
  }
  
  return (
    <Box sx={{ width: '100%' }}>
      <AdaptiveLayout
        backgroundColor={null}
        marginY={0}
        paddingY={0}
        paddingX={0}
        centered={true}
        fullWidth={true}
        useInnerWrapper={false}
      >
        <Typography variant="h4" sx={{ textAlign: 'center', fontWeight: 'bold', mb: 2 }}>
          Premium FSBO Leads for Agents
        </Typography>
        
        <ReferralActionButtons 
          referralLink="premierproperties4you.com"
          showLeaderTextAlways={true}
          fontSize="1.1rem"
          buttonSize="1rem"
          color="primary.main"
        />
      </AdaptiveLayout>
      
      {/* Subscription plans grid */}
      <AdaptiveLayout
        backgroundColor={null}
        marginY={0}
        paddingY={0}
        paddingX={1}
        centered={true}
        fullWidth={true}
        useInnerWrapper={true}
      >
        {plansQuery.isLoading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <Loader />
          </Box>
        ) : plansQuery.isError ? (
          <Typography color="error" sx={{ textAlign: 'center', my: 3 }}>
            {t("planPage.errorLoadingData")}
          </Typography>
        ) : (
          <>
            <Grid container spacing={2} sx={{ maxWidth: '600px' }}>
              {/* Monthly Plans */}
              {monthlyPlans.slice(0, 3).map((plan, index) => (
                <Grid item xs={12} md={4} key={`monthly-${index}`}>
                  <Box sx={{ width: '100%', height: 200 }}>
                    <IOSAppStoreCard
                      titleComponent={createPlanTitleComponent(plan)}
                      subtitleComponent={createPlanSubtitleComponent(plan)}
                      expandedTitleComponent={createExpandedPlanTitleComponent(plan)}
                      expandedSubtitleComponent={createExpandedPlanSubtitleComponent(plan)}
                      borderRadius={4}
                      backdropColor="#40d47e"
                      backdropOpacity={1}
                      paddingX={1.5}
                      paddingY={1.5}
                    />
                  </Box>
                </Grid>
              ))}
            </Grid>
        
            {/* Business-themed CTA */}
            <CtaContainer>
              <CtaTitle>
                Elevate Your Real Estate Business Today
              </CtaTitle>
              <CtaDescription>
                Get exclusive access to qualified FSBO leads and grow your client base with our premium subscription plans.
              </CtaDescription>
              <CtaButton>
                Start Your 14-Day Free Trial
              </CtaButton>
            </CtaContainer>
          </>
        )}
      </AdaptiveLayout>
      
      <AdaptiveLayout
        backgroundColor={null}
        marginY={0}
        paddingY={0}
        paddingX={0}
        centered={true}
        fullWidth={true}
        useInnerWrapper={true}
      >
        <SliderInfo 
          darkMode={darkMode}
          sliderWidth={120}
        />
      </AdaptiveLayout>
    </Box>
  );
};

export default HomePage;